package org.zhuzx.util;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzx 2022-11-04
 */
@Component
@ConditionalOnBean(RedissonClient.class)
public class RedissonCache {

	private static final Logger log = LoggerFactory.getLogger(RedissonCache.class);

	@Autowired
	private RedissonClient redissonClient;
	private static RedissonClient redisson;
	
	@PostConstruct
	private void init() {
		redisson = redissonClient;
		log.info("已注入RedissonClient实例");
	}

	/**
	 * expireMinutes不能传0，会报错：ERR invalid expire time in psetex
	 */
	public static <T> void set(String key, T value, int expireMinutes) {
		RBucket<T> bucket = redisson.getBucket(key);
		bucket.set(value, expireMinutes, TimeUnit.MINUTES);
	}

	/**
	 * 永不过期
	 */
	public static <T> void set(String key, T value) {
		set(key, value, Integer.MAX_VALUE);
	}

	public static <T> T get(String key) {
		RBucket<T> bucket = redisson.getBucket(key);
		return bucket.get();
	}

	public static void remove(String key) {
		redisson.getBucket(key).delete();
	}

}